package com.vnp.cooking;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.vnp.cooking.adapter.ListCachlamAdapter;
import com.vnp.cooking.adapter.ListCachlamAdapter.Holder;
import com.vnp.cooking.adapter.ListCachlamTestAdapter;
import com.vnp.cooking.bean.ObjCachlam;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.PreferenceHelper;

public class CacBuocThucHienActivity extends Activity implements OnClickListener, OnDragListener{
	
	ImageButton btnBack;
	Button btnSave;
	private GridView gridview;
	View main;
	
//	ImageButton btnThembuoc;
	
	ListCachlamAdapter adapter;
//	ListCachlamTestAdapter adapter;
	ImageButton btnThemanh;
	int last;
	boolean isProccess = false;
	boolean isPosted = false;
	ProgressDialog progressDialog;
	Handler mHandler = new Handler();
	Dialog d, dArlert, dChuapost;
	
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			saveStepCT();
		}
	};
	
	Runnable rThoat = new Runnable() {
		
		@Override
		public void run() {
			closeActivity();
		}
	};
	
	int size;
	
	private int draggedIndex = -1;
	
	public static ArrayList<ObjCachlam> objSteps = new ArrayList<ObjCachlam>();
	public static int stepCount =objSteps.size();
	JSONArray step;
	PreferenceHelper preferenceHelper;
	private android.widget.LinearLayout.LayoutParams layoutParams;
	
	float dragPostionX;
	float dragPostionY;
	int myLastVisiblePos;
	private static final String SCREEN_LABEL = "Cac buoc thuc hien screen";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cac_buoc_thuc_hien);
		main = (View) findViewById(R.id.main_grid);
		
		size = objSteps.size();
		
		preferenceHelper = new PreferenceHelper(this);
		
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnSave = (Button) findViewById(R.id.btn_luu_buoc);
//		btnThembuoc = (ImageButton) findViewById(R.id.btn_them);
		gridview = (GridView) findViewById(R.id.grid_buoc_lam);
//		gridview.setLongClickable(true);
		init();
		gridview.setOnItemLongClickListener(new MyClickListener());
		gridview.setOnDragListener(new MyDragListener());
		myLastVisiblePos = gridview.getFirstVisiblePosition();
		gridview.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int arg1) {
		       
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				 int currentFirstVisPos = view.getFirstVisiblePosition();
			        if(currentFirstVisPos > myLastVisiblePos) {
			            //scroll down
			        	
//			        	gridview.setSelection(currentFirstVisPos);
			        }
			        if(currentFirstVisPos < myLastVisiblePos) {
			            //scroll up
			        	if (firstVisibleItem == 0){
//			        		adapter.notifyDataSetChanged();
			        		gridview.setAdapter(adapter);
			        	}
			        }
			        myLastVisiblePos = currentFirstVisPos;
			}
		});
		
		ApplicationContext.getGaTracker().set(Fields.SCREEN_NAME, SCREEN_LABEL);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		ApplicationContext.getGaTracker().send(MapBuilder.createAppView().build());
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	
	void init() {
		
		adapter = new ListCachlamAdapter(CacBuocThucHienActivity.this, objSteps);
		gridview.setAdapter(adapter);
//		gridview.setSelection(objSteps.size());
//		onDragDrop();
		
		btnBack.setOnClickListener(this);
		btnSave.setOnClickListener(this);
//		btnThembuoc.setOnClickListener(this);
		
	}
	
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			if (isProccess == true) {
				showDialogProcess();
			} else {
				if(objSteps.size() == 0) {
					closeActivity();
					objSteps.clear();
				} else {
					if (isPosted == true) {
						closeActivity();
					} else {
						if (size != objSteps.size()) {
							showDialogCanhbaochuapost();
						} else {
							closeActivity();
						}
						
					}
					
				}
				
				
				
			}
			break;
		case R.id.btn_luu_buoc:
			luubuoc();
			break;
			
		/*case R.id.btn_thembuoc:
			addBuoclam();
			break;*/
		case R.id.btn_them:
			chitietBuoc();
			break;
		default:
			break;
		}
	}
	
	void luubuoc() {
		isProccess = true;
		progressDialog = ProgressDialog.show(CacBuocThucHienActivity.this, "", "Đang lưu các bước thực hiện...");
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				if (null != progressDialog && progressDialog.isShowing())
					progressDialog.dismiss();
				Toast.makeText(CacBuocThucHienActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
			}
		}, 90000);
		// goi ham luu
		
		mHandler.removeCallbacks(r);
		mHandler.post(r);
	}
	
	
	void chitietBuoc() {
		Intent t = new Intent(this, TungbuocthuchienActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
	
	public JSONArray createDataStep(){
		step = new JSONArray();
		if (objSteps.size() == 0) {
			
		} else {
			for (int i = 0; i < objSteps.size(); i++) {
				objSteps.get(i).setStep(i+1);
				step.put(objSteps.get(i).getJsonObject());
			}
		}
		
		return step;
	}
	
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
		/*if (stepCount < objSteps.size()) {
			TranslateAnimation animation = new TranslateAnimation(0.0f, 200.0f,
				    0.0f, 0.0f);
			animation.setDuration(500);
			animation.setRepeatMode(2);
			animation.setFillAfter(true);
			btnThembuoc.startAnimation(animation);
		}*/
//		adapter.setDataChange(objSteps);
//		adapter.notifyDataSetChanged();
		gridview.setAdapter(adapter);
		gridview.setSelection(objSteps.size());
//		gridview.setSelection(objSteps.size());
		stepCount = objSteps.size();
		createDataStep();
	
		Log.i("DATA", "JSONARRAY: "+step);
	}
	


	void closeActivity(){
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
		stepCount = 0;
	}


	@Override
	public void onBackPressed() {
		if (isProccess == true) {
			showDialogProcess();
		} else {
			if(objSteps.size() == 0) {
				closeActivity();
//				objSteps.clear();
			} else {
				if (isPosted == true) {
					closeActivity();
//					objSteps.clear();	
				} else {
					showDialogCanhbaochuapost();
				}
				
			}
		}
	}
	
	// luu thu tu cac buoc cong thuc
	void saveStepCT() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				progressDialog.dismiss();
				isProccess = false;
				Toast.makeText(CacBuocThucHienActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onSuccess(JSONObject re) {
				progressDialog.dismiss();
				isProccess = false;
				try {
					int status = re.getInt("status");
					switch (status) {
					case 200:
						isPosted = true;
						mHandler.postDelayed(rThoat, 200);
						Toast.makeText(CacBuocThucHienActivity.this, "Cập nhật thành công.", Toast.LENGTH_SHORT).show();
						break;
						
					case 400:
						Toast.makeText(CacBuocThucHienActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
						break;
					case 404:
						Toast.makeText(CacBuocThucHienActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
						break;
					}
				} catch (JSONException e) {
					Toast.makeText(CacBuocThucHienActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
			}
			
		});
		httpClientHelper.saveStepCT(preferenceHelper.getID(), preferenceHelper.getRecipeId(), step);
	}
	
	// show dialog dang thuc hien 1 hanh dong noa do
		public void showDialogProcess() {
			dArlert = new Dialog(CacBuocThucHienActivity.this,
					R.style.DialogSlideAnimLeft);
			dArlert.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dArlert.setContentView(R.layout.dialog_thoat_process);

			// khai bao cac thanh phan
			TextView txtArlert = (TextView) dArlert
					.findViewById(R.id.str_canhbao_thoat);
			Button btnThoat = (Button) dArlert.findViewById(R.id.btn_thoat);
			Button btnKoThoat = (Button) dArlert.findViewById(R.id.btn_ko_thoat);

			btnThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dArlert.dismiss();
//					objSteps.clear();
					mHandler.removeCallbacks(r);
					mHandler.removeCallbacks(rThoat);
					mHandler.postDelayed(rThoat, 200);
				}
			});

			btnKoThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dArlert.dismiss();
				}
			});

			dArlert.setCanceledOnTouchOutside(true);
			dArlert.show();
			dArlert.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dArlert.getWindow().setGravity(Gravity.CENTER);
		}

		void showDialogCanhbaochuapost() {
			dChuapost = new Dialog(CacBuocThucHienActivity.this,
					R.style.DialogSlideAnimLeft);
			dChuapost.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dChuapost.setContentView(R.layout.dialog_thoat_process);

			// khai bao cac thanh phan
			TextView txtArlert = (TextView) dChuapost
					.findViewById(R.id.str_canhbao_thoat);
			Button btnCapnhatThoat = (Button) dChuapost.findViewById(R.id.btn_thoat);
			Button btnKoCapnhatThoat = (Button) dChuapost.findViewById(R.id.btn_ko_thoat);

			txtArlert
					.setText("Bạn chưa cập nhật các bước thực hiện. Bạn có muốn cập nhật và thoát?");
			btnCapnhatThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dChuapost.dismiss();
//					objSteps.clear();
					luubuoc();
				}
			});

			btnKoCapnhatThoat.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dChuapost.dismiss();
					mHandler.postDelayed(rThoat, 200);
				}
			});

			dChuapost.setCanceledOnTouchOutside(true);
			dChuapost.show();
			dChuapost.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dChuapost.getWindow().setGravity(Gravity.CENTER);
		}



		@Override
		public boolean onDrag(View v, DragEvent event) {
			return false;
		}
		boolean containsDragable;
		class MyDragListener implements OnDragListener{

			@Override
			public boolean onDrag(View v, DragEvent dragEvent) {
				int dragAction = dragEvent.getAction();
		        View dragView = (View) dragEvent.getLocalState();
		        
		        DisplayMetrics displaymetrics = new DisplayMetrics();
		        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		        int height = displaymetrics.heightPixels;
		        int width = displaymetrics.widthPixels;
		        
		        int x = (int) dragEvent.getX();
                int y = (int) dragEvent.getY();
		        GridView parent = (GridView) v;
		        int position = parent.pointToPosition(x, y);
		        
		        
		        
		        if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
		            containsDragable = false;
		        } else if (dragAction == DragEvent.ACTION_DRAG_ENTERED) {
		            containsDragable = true;
		        } else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
		            if (dropEventNotHandled(dragEvent)) {
		                dragView.setVisibility(View.VISIBLE);
		            }
		        } else if (dragAction == DragEvent.ACTION_DROP && containsDragable) {
		        	Log.i("DATA", ""+dragEvent.getY()+"HEIGHT: "+height);
		        	if (dragEvent.getLocalState() == v) {
		        		return true;	
		        	} else {
		        		if (dragEvent.getY() > (height - height/5)){
			        		objSteps.remove(draggedIndex);
			        		adapter.notifyDataSetChanged();
			        		gridview.setAdapter(adapter);
			        	} else {
			        		dragView.setVisibility(View.VISIBLE);
						}
		        		
		        		/*ObjCachlam dropItem = ((Holder) dragView.getTag()).objCachlam;
			        	
			        	ListCachlamAdapter adapter = (ListCachlamAdapter) parent.getAdapter();
			        	objSteps = adapter.getItems();
			        	
			        	View target = v;
			        	ObjCachlam targetItem = ((Holder) target.getTag()).objCachlam;
			        	int index = objSteps.indexOf(targetItem);
			        	objSteps.remove(dropItem);
			        	objSteps.add(index, dropItem);
			        	adapter.notifyDataSetChanged(); */
					}
		        	
		        }
		        return true;
			}
			
		}
		
		/*private void checkForValidMove(ChessBoardSquareLayoutView view, View dragView) {
	        if (mediator.isValidMove(view)) {
	            ViewGroup owner = (ViewGroup) dragView.getParent();
	            owner.removeView(dragView);
	            view.addView(dragView);
	            view.setGravity(Gravity.CENTER);
	            view.showAsLanded();
	            mediator.handleMove(view);
	        }
	    }*/
		private boolean dropEventNotHandled(DragEvent dragEvent) {
	        return !dragEvent.getResult();
	    }
		
		private final class MyClickListener implements OnItemLongClickListener{

			@Override
			public boolean onItemLongClick(AdapterView<?> p, View view,
					int position, long id) {
				/*ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());
				 String[] mimeTypes = { ClipDescription.MIMETYPE_TEXT_PLAIN };
	             ClipData data = new ClipData(v.getTag().toString(), mimeTypes, item);
	             DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
	         
	             v.startDrag( data, //data to be dragged
	                             shadowBuilder, //drag shadow
	                             v, //local data about the drag and drop operation
	                             0   //no needed flags
	                           );*/
				
				GridView parent = (GridView)p;
				int relativePosition = position - parent.getFirstVisiblePosition();
				View target = (View) parent.getChildAt(relativePosition);

                Holder  holder = (Holder) target.getTag();
                ObjCachlam currentItem = holder.objCachlam;
				
				
				draggedIndex = position;
				ClipData clipData = ClipData.newPlainText("", "");
	            View.DragShadowBuilder dsb = new View.DragShadowBuilder(target);
	            view.startDrag(clipData, dsb, target, 0);
	            dragPostionX = view.getX();
	            dragPostionY = view.getY();
	            view.setVisibility(View.INVISIBLE);
	            return true;
			}

			
		}

		void onDragDrop(){
			gridview.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					 if (event.getAction() == MotionEvent.ACTION_DOWN) {
			                GridView parent = (GridView) v;

			                int x = (int) event.getX();
			                int y = (int) event.getY();

			                int position = parent.pointToPosition(x, y);
			                if (position > AdapterView.INVALID_POSITION) {

			                    int count = parent.getChildCount();
			                    for (int i = 0; i < count; i++) {
			                        View curr = parent.getChildAt(i);
			                        curr.setOnDragListener(new View.OnDragListener() {

			                            @Override
			                            public boolean onDrag(View v, DragEvent event) {

			                                boolean result = true;
			                                int action = event.getAction();
			                                
			                                DisplayMetrics displaymetrics = new DisplayMetrics();
			                		        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
			                		        int height = displaymetrics.heightPixels;
			                		        int width = displaymetrics.widthPixels;
			                                
			                                
			                                switch (action) {
			                                case DragEvent.ACTION_DRAG_STARTED:
			                                    break;
			                                case DragEvent.ACTION_DRAG_LOCATION:
			                                    break;
			                                case DragEvent.ACTION_DRAG_ENTERED:
			                                    break;
			                                case DragEvent.ACTION_DRAG_EXITED:
			                                    break;
			                                case DragEvent.ACTION_DROP:
			                                    if (event.getLocalState() == v) {
			                                        result = false;
			                                    } else {
			                                    	
			                                    	if (event.getY() > (height - height/5)){
			                			        		objSteps.remove(draggedIndex);
			                			        		adapter.notifyDataSetChanged();
			                			        		Log.i("DATA", "-------------1");
			                			        	} else {
			                			        		Log.i("DATA", "-------------2");
														v.setVisibility(View.VISIBLE);
													}
			                                    	
			                                    	Log.i("DATA", "-------------3");
			                                        View droped = (View) event.getLocalState();
			                                        ObjCachlam dropItem = ((Holder) droped.getTag()).objCachlam;

			                                        GridView parent = (GridView) droped.getParent();
			                                        ListCachlamAdapter adapter = (ListCachlamAdapter) parent.getAdapter();
			                                        objSteps = adapter.getItems();

			                                        View target = v;
			                                        ObjCachlam targetItem = ((Holder) target.getTag()).objCachlam;
//			                                        int index = objSteps.indexOf(targetItem);
//			                                        objSteps.remove(dropItem);
			                                        objSteps.add(0, dropItem);
			                                        adapter.notifyDataSetChanged();
			                                    }
			                                    break;
			                                case DragEvent.ACTION_DRAG_ENDED:
			                                	 if (dropEventNotHandled(event)) {
			                 		                v.setVisibility(View.VISIBLE);
			                 		            }
			                                    break;
			                                default:
			                                    result = false;
			                                    break;
			                                }
			                                return result;
			                            }
			                        });
			                    }

			                    int relativePosition = position - parent.getFirstVisiblePosition();


			                    View target = (View) parent.getChildAt(relativePosition);

			                    Holder holder = (Holder) target.getTag();
			                    ObjCachlam currentItem = holder.objCachlam;
//			                    String text = currentItem.getFile().getAbsolutePath();
			                    ClipData data = ClipData.newPlainText("DragData", "");
			                    target.startDrag(data, new View.DragShadowBuilder(target), target, 0);
			                }
			            }
					return true;
				}
			});
		}
}
